#include "uthread.h"

struct barrier{
    int n;
    int counter;
    struct binary_semaphore *arrival;
    struct binary_semaphore *departure;
};

void barrier_init(struct barrier* b, int n)
{
    b->counter = 0;
    b->n = n;
    b->arrival = malloc(sizeof(struct binary_semaphore));
    binary_semaphore_init(b->arrival,1);		// arrival=1
    b->departure = malloc(sizeof(struct binary_semaphore));
    binary_semaphore_init(b->departure,0);		// departure=0;
}

void barrier_pass(struct barrier* b)
{
   binary_semaphore_down(b->arrival);
   //printf(1,"someone has crossed the barrier arrival\n");
   b->counter++;
   if( (b->counter) < (b->n) )
   {
	//printf(1,"someone is lifting the barrier arrival\n");
	binary_semaphore_up(b->arrival);
   }
   else 
   {
	//printf(1,"someone is lifting the barrier departure for the first time this round\n");
	binary_semaphore_up(b->departure);
   }
   binary_semaphore_down(b->departure);
   //printf(1,"someone has  crossed the barrier departure\n");
   b->counter--;
   if(b->counter > 0) 
   {
	//printf(1,"someone is lifting the barrier departure\n");
	binary_semaphore_up(b->departure);
   }
   else 
   {
	//printf(1,"someone is lifting the barrier arrival for the last time this round\n");
	binary_semaphore_up(b->arrival);
   }
}
